<template>
  <el-checkbox-group
    v-if="multiple && checkbox"
    :style="{ width }"
    :disabled="disabled"
    class="dict-checkbox-group"
    v-model="selectOptions"
    :size="parseInt(width) >= 350 ? 'large' : 'default'"
  >
    <el-checkbox
      class="checkbox-empty"
      label="0"
      border
      v-if="allowEmpty"
      @change="onLimitChange"
    >
      不限
    </el-checkbox>
    <el-checkbox
      v-for="item in data"
      :key="item.value"
      :label="String(item.value)"
      border
      @change="onChange"
    >
      <div class="flex items-center">
        <span class="pr-1">{{ item.label }}</span>
      </div>
    </el-checkbox>
  </el-checkbox-group>
  <el-select
    v-else
    class="dict-select"
    :style="{ width }"
    v-model="selectOptions"
    :placeholder="placeholder"
    :size="parseInt(width) >= 350 ? 'large' : 'default'"
    tag-type="danger"
    tag-effect="light"
    :filterable="data.length > 10 || allowCreate"
    :collapse-tags="multiple"
    :collapse-tags-tooltip="multiple"
    :max-collapse-tags="10"
    :clearable="clearable"
    :multiple="multiple"
    :disabled="disabled"
    :allow-create="!isNumber && allowCreate"
  >
    <el-option
      v-for="item in data"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
    <template #footer v-if="slots.footer">
      <slot name="footer"></slot>
    </template>
  </el-select>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch, useSlots } from "vue"
import { getDictApi } from "@/api/dicts"
import _ from "lodash"

const slots = useSlots()

defineOptions({
  name: "dictSelect",
})

const emit = defineEmits(["update:modelValue", "change"])
const props = defineProps({
  modelValue: {
    type: [String, Array, Number],
    default: "",
  },
  placeholder: {
    type: String,
    default: "请选择",
  },
  clearable: {
    type: Boolean,
    default: false,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  type: {
    //字典的type
    type: String,
    default: "",
  },
  isNumber: {
    type: Boolean,
    default: false,
  },
  allowEmpty: {
    type: Boolean,
    default: false,
  },
  allowCreate: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Array,
    default: () => [],
  },
  checkbox: {
    type: Boolean,
    default: false,
  },
  index: {
    type: Number,
    default: -1,
  },
  width: {
    type: String,
    default: "650px",
  },
})

interface DataItem {
  value: string
  label: string
}

const data = ref([] as DataItem[])
// const list = computed(() => {
//     // if (props.extend) {
//     //     // console.log(props.extend);
//     //     const list = data.value.filter((item: any) => item?.extend === props.extend)
//     //     if (list.length === 1 && !props.multiple) {
//     //         // selectOptions.value = list[0]['value'];
//     //         emit('update:modelValue', list[0]['value']);
//     //     }
//     //     return list;
//     // }
//
//     //允许创建新值时，未查询到value则插入进去
//     if (!props.multiple && !props.isNumber && props.allowCreate && data.value.find((item: any) => item?.value === selectOptions.value) == null) {
//         return [...(data.value), {label: selectOptions.value, value: selectOptions.value}].filter(item => item.value);
//     }
//     return data.value;
// });
// const desc = computed(() => data.value.find(item => item.value === selectOptions.value)?.desc)
const selectOptions = computed({
  get() {
    const modelValue = props.modelValue as any
    if (props.multiple && typeof modelValue === "string") {
      return modelValue ? modelValue.split(",") : []
    }
    return props.multiple
      ? modelValue
      : String(modelValue === null ? "" : modelValue)
  },
  set(val: any) {
    const modelValue = props.modelValue as any
    if (props.multiple && typeof modelValue === "string") {
      emit("update:modelValue", val ? val.join(",") : "")
    } else {
      emit("update:modelValue", props.isNumber && val >= 0 ? Number(val) : val)
    }
    if (props.multiple) {
      emit("change", val)
    } else {
      emit(
        "change",
        val,
        data.value.find((item: DataItem) => item.value === val),
        props.index,
      )
    }
  },
})

//不限制勾选时，清空其他
const onLimitChange = (val: string) => {
  if (val && props.allowEmpty) {
    const list = selectOptions.value.filter((item: string) => item === "0")
    emit("update:modelValue", list.join(","))
  }
}

//普通勾选时，清空0
const onChange = (val: string) => {
  if (val && props.allowEmpty) {
    const list = selectOptions.value.filter((item: string) => item !== "0")
    emit("update:modelValue", list?.length ? list.join(",") : "0")
  }
}

watch(
  () => props.data,
  (val: any) => {
    const _val = _.cloneDeep(val || [])
    _val.map((item: DataItem) => {
      item.value = String(item.value)
    })
    data.value = _val as DataItem[]
  },
  {
    deep: true,
    immediate: true,
  },
)

onMounted(async () => {
  if (props.type) {
    const res: any = await getDictApi(props.type)
    if (res.success) {
      res.data?.map((item: any) => {
        item.value = String(item.value)
      })
      data.value = res.data as DataItem[]
    }
  }
})
</script>

<style lang="scss" scoped>
.dict-checkbox-group {
  display: flex;
  background-color: #f5f7fa;
  border-radius: 6px;

  .el-checkbox {
    display: inline-flex;
    flex: 1;
    align-items: center;
    justify-content: center;
    padding: 0 12px !important;
    margin: 0;
    border: 0;

    --el-checkbox-checked-bg-color: #fff2f2;
    --el-checkbox-checked-input-border-color: #faf2f2;
    --el-checkbox-checked-icon-color: var(--el-color-primary);
    --el-checkbox-font-weight: 400;

    &.checkbox-empty {
      &.is-checked {
        color: var(--el-color-primary);
        background-color: #fff2f2;
      }

      :deep(.el-checkbox__input) {
        display: none !important;
      }
    }
  }
}
</style>
